<template>
  <div>
    <div ref="graphContainer" style="width: 100%; height: 600px; border: 1px solid #eee; border-radius: 4px;"></div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, watch } from 'vue';
import * as echarts from 'echarts';
import { knowledgeGraphApi } from '@/api/recommend.js';

const props = defineProps({
  goodsId: {
    type: [Number, String],
    required: true
  }
});

const graphContainer = ref(null);
let chart = null;
const loading = ref(false);

// 定义节点类型对应的颜色和图标
const categoryMap = {
  'Goods': { color: '#5470c6', symbol: 'circle' },
  'Region': { color: '#91cc75', symbol: 'triangle' },
  'Period': { color: '#fac858', symbol: 'diamond' },
  'CraftSchool': { color: '#ee6666', symbol: 'rect' },
  'Culture': { color: '#73c0de', symbol: 'roundRect' },
  'HistoricalFigure': { color: '#3ba272', symbol: 'pin' },
  'HistoricalEvent': { color: '#fc8452', symbol: 'arrow' }
};

// 格式化节点数据为ECharts格式
const formatNodes = (nodes) => {
  return nodes.map(node => {
    const category = categoryMap[node.label] || { color: '#bbb', symbol: 'circle' };
    // 处理节点ID，支持数字和对象两种形式
    const nodeId = typeof node.id === 'object' && node.id.low !== undefined 
      ? node.id.low.toString() 
      : node.id.toString();
    
    return {
      id: nodeId,
      name: node.properties.name || node.label + '-' + nodeId,
      symbolSize: node.level === 0 ? 30 : 20,
      value: node.properties,
      category: node.label,
      itemStyle: {
        color: category.color
      },
      symbol: category.symbol
    };
  });
};

// 格式化关系数据为ECharts格式
const formatLinks = (relationships) => {
  return relationships.map(rel => {
    // 处理关系的源和目标ID，支持数字和对象两种形式
    const sourceId = typeof rel.source === 'object' && rel.source.low !== undefined 
      ? rel.source.low.toString() 
      : rel.source.toString();
    
    const targetId = typeof rel.target === 'object' && rel.target.low !== undefined 
      ? rel.target.low.toString() 
      : rel.target.toString();
    
    return {
      source: sourceId,
      target: targetId,
      name: rel.type,
      value: rel.properties || {}
    };
  });
};

// 获取知识图谱数据
const fetchGraphData = async () => {
  if (!props.goodsId) return;
  
  loading.value = true;
  try {
    const response = await knowledgeGraphApi(props.goodsId);
    console.log('知识图谱响应:', response);
    
    if (response.code === 200) {
      const graphData = response.data;
      
      if (!graphData || 
          (!graphData.nodes || !graphData.nodes.length) && 
          (!graphData.relationships || !graphData.relationships.length)) {
        console.warn('知识图谱数据为空，商品ID:', props.goodsId);
        showEmptyGraph();
      } else {
        console.log('成功获取知识图谱数据，节点数:', graphData.nodes.length, '关系数:', graphData.relationships.length);
        initGraph(graphData);
      }
    } else {
      console.error('获取知识图谱失败:', response.message);
      showEmptyGraph();
    }
  } catch (error) {
    console.error('获取知识图谱数据失败:', error);
    showEmptyGraph();
  } finally {
    loading.value = false;
  }
};

// 显示空图表
const showEmptyGraph = () => {
  if (!graphContainer.value) return;
  
  if (!chart) {
    chart = echarts.init(graphContainer.value);
  }
  
  const option = {
    title: {
      text: '暂无知识图谱数据',
      left: 'center',
      top: 'center',
      textStyle: {
        fontSize: 20,
        color: '#999'
      }
    }
  };
  
  chart.setOption(option);
};

// 初始化图表
const initGraph = (data) => {
  if (!graphContainer.value) return;
  
  if (!chart) {
    chart = echarts.init(graphContainer.value);
  }
  
  const nodes = formatNodes(data.nodes || []);
  const links = formatLinks(data.relationships || []);
  
  const categories = Object.keys(categoryMap).map(key => ({
    name: key,
    itemStyle: {
      color: categoryMap[key].color
    }
  }));
  
  const option = {
    title: {
      text: '工艺品知识图谱',
      top: 'top',
      left: 'center'
    },
    tooltip: {
      formatter: function(params) {
        if (params.dataType === 'node') {
          const data = params.data;
          let html = `<div>${data.name}</div>`;
          if (data.value) {
            html += '<div style="margin-top:5px;">';
            Object.keys(data.value).forEach(key => {
              if (key !== 'id' && key !== 'name' && data.value[key]) {
                html += `<div>${key}: ${data.value[key]}</div>`;
              }
            });
            html += '</div>';
          }
          return html;
        } else if (params.dataType === 'edge') {
          return `<div>${params.name}</div>`;
        }
      }
    },
    legend: {
      data: categories.map(c => c.name),
      orient: 'vertical',
      left: 'left',
      top: 'middle'
    },
    animationDuration: 1500,
    animationEasingUpdate: 'quinticInOut',
    series: [
      {
        type: 'graph',
        layout: 'force',
        data: nodes,
        links: links,
        categories: categories,
        roam: true,
        label: {
          show: true,
          position: 'right',
          formatter: '{b}'
        },
        force: {
          repulsion: 100,
          edgeLength: 200
        },
        lineStyle: {
          color: 'source',
          curveness: 0.3
        },
        emphasis: {
          focus: 'adjacency',
          lineStyle: {
            width: 4
          }
        }
      }
    ]
  };
  
  chart.setOption(option);
  
  // 响应窗口变化
  window.addEventListener('resize', () => {
    chart && chart.resize();
  });
};

// 监听goodsId变化
watch(() => props.goodsId, (newVal) => {
  if (newVal) {
    fetchGraphData();
  }
});

onMounted(() => {
  fetchGraphData();
});

onUnmounted(() => {
  if (chart) {
    chart.dispose();
    chart = null;
  }
  window.removeEventListener('resize', chart.resize);
});
</script>

<style scoped>
.legend-item {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}
.legend-color {
  width: 15px;
  height: 15px;
  margin-right: 8px;
  border-radius: 3px;
}
</style> 